#!/usr/bin/env python
# -*- coding: utf-8 -*-
#create by yuc

from . import spider
from flask import send_file,make_response
from app.route.verify_common import *
from modules.xiapibuy.xiapibuy import *
from app.models import*
from modules.TimeManage.timetool import timeToStr,str_to_unix_timestamp
from .spider_request import spider_following_requests,spider_itemfollowing_requests

'''
True为可用，未超时
'''
def time_control(str_time):
    times_input = str_to_unix_timestamp(str_time)
    if times_input > time.time():
        return True
    return False

'''
按商品分类进行关注

# 获取输入类别（可以是子分类）
# 指定要关注商铺数量  50整数倍
# 指定全商铺 想关注粉丝总数量 20整数倍
# 并执行关注
{
    'user_appkey':'xxx',
    'cat_id': 62,  #会有对应表
    'auto_switch':'enable'
    'cat_shop_count':50,  #默认50
    'total_shop_follower':20  #默认一次关注20个
}
'''
@spider.route('/following',methods=['POST'])
def spider_following():
    try:
        data = request.get_data(as_text=True)
        json_data =json.loads(data)
       
        #判断当前user_appkey可用
        user_appkey_res = Spiderdb.query.filter(Spiderdb.user_appkey == json_data['user_appkey'])
        if user_appkey_res.count() > 0:
            current_res = user_appkey_res.first()
            #时间控制
            if time_control(current_res.user_time_control) == False:
                return  json.dumps({'status':-5,'msg':u'user_appkey使用时间超时'})
            xp_spider = Xiapibuy()
            xp_spider.xiapi_set_cookie(current_res.user_token)
            if xp_spider.xiapi_get_cookie() == '':
                return  json.dumps({'status':-6,'msg':u'user_token用户登陆信息出现问题'})
            #默认只要1个关注返回即可，判断cookie有效就行
            #res = xp_spider.xiapi_main_run_get_follower(json_data['cat_id'],json_data['cat_shop_count'],json_data['total_shop_follower'])
            res = xp_spider.xiapi_main_run_get_follower(json_data['cat_id'],json_data['cat_shop_count'],1,1)
            #res = {'status':1,'msg':""}
            #cookie失效问题
            if res['status'] == -6:
                return json.dumps(res)
            current_res.user_last_use_time = timeToStr(time.time())
            db.session.commit()
            #创建任务
            spider_following_requests(json_data)

            return json.dumps(res)
        else:
            return json.dumps({'status':-2,'msg':u'没有可用appkey'})
    except Exception as err:
        print('following err:',err,data)
        return json.dumps({'status':-1,'msg':str(err)})

'''
#指定商品
#对此商品的店铺粉丝进行关注
{
    'user_appkey':'xxx',
    'item_url':'xxxx'
}
'''
@spider.route('/itemfollowing',methods=['POST'])
def spider_item_following():
    try:
        data = request.get_data()
        json_data =json.loads(data)
        #todo 针对店铺进行关注 待测试开发
        user_appkey_res = Spiderdb.query.filter(Spiderdb.user_appkey == json_data['user_appkey'])
        if user_appkey_res.count() > 0:
            current_res = user_appkey_res.first()
            if time_control(current_res.user_time_control) == False:
                return  json.dumps({'status':-5,'msg':u'user_appkey使用时间超时'})
            xp_spider = Xiapibuy()
            xp_spider.xiapi_set_cookie(current_res.user_token)
            if xp_spider.xiapi_get_cookie() == '':
                return  json.dumps({'status':-6,'msg':'user_token用户登陆信息出现问题'})
            #res = xp_spider.xiapi_saleitem_get_follower(json_data['item_url'])
            #默认只要1个关注返回即可，判断cookie有效就行
            res = xp_spider.xiapi_saleitem_get_follower(json_data['item_url'],1)
            #res = {'status':1,'msg':""}
            #cookie失效问题
            if res['status'] == -6:
                return json.dumps(res)
            current_res.user_last_use_time = timeToStr(time.time())
            spider_itemfollowing_requests(json_data)
            #db.session.commit()
            return json.dumps(res)
        else:
            return json.dumps({'status':-2,'msg':u'没有可用appkey'})
    except Exception as err:
        print(traceback.print_exc())
        return json.dumps({'status':-1,'msg':str(err)})

'''
#输入店铺token信息
#如果user_appkey存在即可设置，
{
    'user_appkey':'xxx',
    'user_token':'xxx'
}
'''
@spider.route('/settoken',methods=['POST'])
def spider_set():
    try:
        data = request.get_data()
        json_data =json.loads(data)
        user_appkey_res = Spiderdb.query.filter(Spiderdb.user_appkey == json_data['user_appkey'])
        if user_appkey_res.count() >0:
            current_res = user_appkey_res.first()
            if time_control(current_res.user_time_control) == False:
                return  json.dumps({'status':-5,'msg':u'user_appkey使用时间超时'})
            current_res.user_token = json_data['user_token']
            db.session.commit()
            return json.dumps({'status':1,'msg':'settoken ok'})
        return json.dumps({'status':-2,'msg':u'没有可用appkey'})
    except Exception as err:
        print('err:',err)
        return json.dumps({'status':-1,'msg':str(err)})





#测试
@spider.route('/followingtest',methods=['POST'])
def spider_url_uploadtest():
    try:
        data = request.get_data()
        json_data =json.loads(data)
        #todo 针对店铺进行关注 待测试开发
        user_appkey_res = Spiderdb.query.filter(Spiderdb.user_appkey == json_data['user_appkey'])
        if user_appkey_res.count() > 0:
            current_res = user_appkey_res.first()
            if time_control(current_res.user_time_control) == False:
                return  json.dumps({'status':-5,'msg':u'user_appkey使用时间超时'})
            xp_spider = Xiapibuy()
            xp_spider.xiapi_set_cookie(current_res.user_token)
            if xp_spider.xiapi_get_cookie() == '':
                return  json.dumps({'status':-6,'msg':'user_token用户登陆信息出现问题'})
            #res = xp_spider.xiapi_saleitem_get_follower(json_data['item_url'])
            res = {}
            current_res.user_last_use_time = timeToStr(time.time())
            db.session.commit()
            return json.dumps(res)
        else:
            return json.dumps({'status':-2,'msg':u'没有可用appkey'})
    except Exception as err:
        print(traceback.print_exc())
        return json.dumps({'status':-1,'msg':str(err)})